linux时间同步配置

系统层面(离线)

先查看当前系统时间

root@ubuntu:/# date -R 结果时区是:-0500 我需要的是东八区,这儿显示不是,所以需要设置一个时区

img

时区设置

1.运行tzselect

root@ubuntu:/# tzselect

img

在这里我们选择亚洲 Asia,确认之后选择中国(China),最后选择北京(Beijing)

img
2.复制文件到/etc目录下

root@ubuntu:/# cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

3.再次查看时间date -R,已经修改为北京时间
img

时间设置

sudo date -s MM/DD/YY //修改日期 sudo date -s hh:mm:ss //修改时间 在修改时间以后,修改硬件CMOS的时间

sudo hwclock --systohc //非常重要,如果没有这一步的话,后面时间还是不准

系统时间与硬件时间同步

# 检查系统时间和硬件时间
date
hwclock --show
# 从硬件时钟同步到系统时间
hwclock --hctosys
# 验证同步结果
date -R
hwclock --show

常用的 hwclock 命令说明

# 从硬件时钟同步到系统时间
hwclock --hctosys
# 或者简写
hwclock -s

# 从系统时间同步到硬件时钟
hwclock --systohc
# 或者简写
hwclock -w

# 显示硬件时间
hwclock --show

网络层面-时间同步服务(在线)

检查网络和防火墙

# 检查网络连接
ping pool.ntp.org

# 检查防火墙是否阻止NTP(端口123)
firewall-cmd --list-all

方案一:使用timedatectl(较老机型)

# 启用NTP时间同步
timedatectl set-ntp true

# 手动设置正确时间(如果需要)
timedatectl set-time "2025-11-21 10:01:00"

# 检查状态
timedatectl status

方案二:使用chronyd服务(推荐)

# 启动并启用chronyd服务
systemctl start chronyd
systemctl enable chronyd
# 配置NTP服务器(编辑 /etc/chrony.conf)
echo "server ntp1.aliyun.com iburst" >> /etc/chrony.conf
echo "server ntp2.aliyun.com iburst" >> /etc/chrony.conf
# 重启chronyd服务
systemctl restart chronyd
# 强制同步时间
chronyd sources -v
chronyd -q 'server pool.ntp.org iburst'

方案三:使用ntpdate手动同步

# 安装ntpdate(如果没有)
yum install -y ntpdate

# 手动同步时间
ntpdate -s pool.ntp.org
# 或使用国内NTP服务器
ntpdate -s ntp1.aliyun.com

# 将系统时间写入硬件时钟
hwclock --systohc

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部